import filters from '@/filters/common.js'
import store from '@/store/index.js'

// 跳转
function navTo(url, opentype = 'navigateTo', animationType = 'pop-in') {
	const pageName = url.split('?')[0]
	const noLoginPages = [
		'/pages/index/index',
		'/pages/user/login', 
		'/pages/user/register-role', 
		'/pages/user/register-enterprise',
		'/pages/user/register-user',
		'/pages/user/forget-password', 
		'/pages/other/richText',
		'/pages/other/platform-rule',
		'/pages/other/help',
		'/pages/product/search',
		'/pages/product/list-product',
		'/pages/demand/detail-demand',
		'/pages/merchant/detail',
		'/pages/merchant/ranking',
		'/pages/mine/index',
		'/pages/category/index',
		'/pages/message/index'
	]
	console.log(store.getters.isLogin);
	// 需要登录
	if (noLoginPages.indexOf(pageName) == -1 && !store.getters.isLogin) {
		uni.showModal({
			title: '提示',
			content:'您还未登录，是否去登录？',
			success:res => {
				if(res.confirm){
					uni.navigateTo({
						url:'/pages/user/login'
					})
				}
			}
		})
		
	} else {
		uni[opentype]({
			url,
			animationType
		})
	}
}

/**回退到某个页面
 * @param {Object} backUrl 页面绝对路径 /pages/index/...
 */
function backTo(backUrl){
	const pages = getCurrentPages()	
	const backPageIndex = pages.findIndex(item => item.$page.fullPath.indexOf(backUrl) !== -1)
	if(backPageIndex > -1){
		uni.navigateBack({
			delta: pages.length - backPageIndex - 1
		})
	}else{
		console.warn('未找到要返回的页面')
	}
}


// 提示
function toast(title, mask = false, icon = 'none', duration = 1500) {
	uni.showToast({
		icon,
		mask,
		title,
		duration
	})
}

// 预览图片
function previewImages(images, index) {
	if (!Array.isArray(images)) {
		images = images.split(',')
	}
	const newImages = images.map(item => filters.formatFile(item))
	uni.previewImage({
		current: index, //预览图片的下标
		urls: newImages //预览图片的地址，必须要数组形式，如果不是数组形式就转换成数组形式就可以
	})
}

// 拨打电话
function phoneCall(val) {
	uni.makePhoneCall({
		phoneNumber: val
	})
}

// 获取位置信息
// H5端 IOS如果在本地调试需要将manifest.json中 "启用https协议"开启，访问本地 https才可以，否则成功和失败回调都进不去
function getLocation() {
	return new Promise((resolve, reject) => {
		uni.getLocation({
			type: 'gcj02',
			success: res => {
				resolve(res)
			},
			fail: err => {
				toast(err)
				reject(err)
			}
		});
	})
}


export {
	navTo,
	backTo,
	toast,
	phoneCall,
	previewImages,
	getLocation
}